<script setup>
import { ref } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { adminCreateVolunteerService } from '@/api/volunteer.js'
import { useUserStore } from '@/stores'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

const userStore = useUserStore()
const volunteerInfo = ref({
  activityName: '',
  organization: '',
  activityLocation: '',
  linkman: '',
  contact: '',
  beginTime: '',
  endTime: '',
  recruitNumber: 0,
  recruitmentPositions: '',
  enrollmentRestrictions: '',
  registrationDeadline: '',
  eventDescription: '',
  eventContent: '',
  eventPhoto: '',
  tag: ''
})
const SubmitVolunteer = async () => {
  console.log(volunteerInfo.value)
  // 表单验证
  if (!volunteerInfo.value.activityName) {
    message.error('请填写志愿活动名称')
    return
  }
  if (!volunteerInfo.value.organization) {
    message.error('请填写发布组织')
    return
  }
  if (!volunteerInfo.value.activityLocation) {
    message.error('请填写活动地点')
    return
  }
  if (!volunteerInfo.value.linkman) {
    message.error('请填写联系人')
    return
  }
  if (!volunteerInfo.value.contact) {
    message.error('请填写联系方式')
    return
  }
  if (!volunteerInfo.value.tag) {
    message.error('请填写活动标签')
    return
  }
  if (!volunteerInfo.value.beginTime || !volunteerInfo.value.endTime) {
    message.error('请选择活动时间')
    return
  }
  if (!volunteerInfo.value.recruitNumber) {
    message.error('请填写招募人数')
    return
  }
  if (!volunteerInfo.value.recruitmentPositions) {
    message.error('请填写招募岗位')
    return
  }
  if (!volunteerInfo.value.enrollmentRestrictions) {
    message.error('请填写报名限制')
    return
  }
  if (!volunteerInfo.value.eventDescription) {
    message.error('请填写活动简介')
    return
  }
  if (!volunteerInfo.value.eventContent) {
    message.error('请填写活动内容')
    return
  }
  if (!volunteerInfo.value.eventPhoto) {
    message.error('请上传活动图片')
    return
  }

  const res = await adminCreateVolunteerService(volunteerInfo.value)
  if (res.data.code === 1) {
    message.success('志愿活动创建成功！')
    volunteerInfo.value = {
      activityName: '',
      organization: '',
      activityLocation: '',
      linkman: '',
      contact: '',
      beginTime: '',
      endTime: '',
      recruitNumber: 0,
      recruitmentPositions: '',
      enrollmentRestrictions: '',
      registrationDeadline: '',
      eventDescription: '',
      eventContent: '',
      eventPhoto: '',
      tag: ''
    }
    fileList.value = []
    timeStorage.value = []
    timeStorage2.value = null
  } else {
    message.error('志愿活动提交失败！')
  }
}
//-------时间选择器相关---------
// 禁用当前时间之前的日期和时间
const disabledDate = (current) => {
  return current && current < dayjs().startOf('day')
}

const disabledTime = (current) => {
  if (!current) return {}
  const now = dayjs()
  if (current.isSame(now, 'day')) {
    return {
      disabledHours: () => Array.from({ length: now.hour() }, (_, i) => i),
      disabledMinutes: () =>
        now.hour() === current.hour()
          ? Array.from({ length: now.minute() }, (_, i) => i)
          : [],
      disabledSeconds: () => []
    }
  }
  return {}
}
// 时间选择器变化事件
const timeStorage = ref([])
const handleTimeChange = (value) => {
  if (Array.isArray(value)) {
    volunteerInfo.value.beginTime = dayjs(value[0]).format(
      'YYYY-MM-DD HH:mm:ss'
    )
    volunteerInfo.value.endTime = dayjs(value[1]).format('YYYY-MM-DD HH:mm:ss')
  }
}
const timeStorage2 = ref(null)
const handleTimeChange2 = (value) => {
  timeStorage2.value = value
  volunteerInfo.value.registrationDeadline = value
    ? dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    : ''
}
//----------图片上传相关------------
const fileList = ref([])
const headers = {
  adminToken: userStore.token
}
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const loading = ref(false)
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
const handlePreview = async (file) => {
  previewVisible.value = true
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
const handleChange = (info) => {
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }
  if (info.file.status === 'done') {
    loading.value = false
    message.success(`${info.file.name} 文件上传成功！`)
    volunteerInfo.value.eventPhoto = info.file.response.data
    previewImage.value = info.file.response.data
  }
  if (info.file.status === 'error') {
    loading.value = false
    message.error('上传失败！')
  }
}
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('图片格式有误!')
  }
  const isLtSize = file.size / 1024 / 1024 < 4
  if (!isLtSize) {
    message.error('图片大小必须小于4MB!')
  }
  return isJpgOrPng && isLtSize
}
//string转number
const handleInput = (event) => {
  const value = event.target.value
  // 将输入的值转换为数字，非数字值保持为空或其他默认值
  volunteerInfo.value.recruitNumber = value === '' ? '' : Number(value)
}
</script>

<template>
  <div>
    <h2><b>活动基础信息</b></h2>
    <span>志愿活动名称</span>
    <a-input-group compact>
      <a-input v-model:value="volunteerInfo.activityName" style="width: 50%" />
    </a-input-group>
    <span>发布组织</span>
    <a-input-group compact>
      <a-input v-model:value="volunteerInfo.organization" style="width: 50%" />
    </a-input-group>
    <span>活动地点</span>
    <a-input-group compact>
      <a-input
        v-model:value="volunteerInfo.activityLocation"
        style="width: 50%"
      />
    </a-input-group>
    <span>联系人</span>
    <a-input-group compact>
      <a-input v-model:value="volunteerInfo.linkman" style="width: 30%" />
    </a-input-group>
    <span>联系方式</span>
    <a-input-group compact>
      <a-input v-model:value="volunteerInfo.contact" style="width: 30%" />
    </a-input-group>
    <span>活动标签</span>
    <a-input-group compact>
      <a-input
        v-model:value="volunteerInfo.tag"
        style="width: 30%"
        placeholder="如：社区服务,关爱青少年,科学科普等，多个标签用逗号隔开"
      />
    </a-input-group>
    <h2><b>志愿者招募详情</b></h2>
    <span>活动时间</span>
    <a-input-group compact>
      <a-range-picker
        v-model:value="timeStorage"
        style="width: 400px"
        :disabled-date="disabledDate"
        :disabled-time="disabledTime"
        :show-time="{
          hideDisabledOptions: true,
          defaultValue: [
            dayjs('00:00:00', 'HH:mm:ss'),
            dayjs('23:59:59', 'HH:mm:ss')
          ]
        }"
        format="YYYY-MM-DD HH:mm:ss"
        @change="handleTimeChange"
      />
    </a-input-group>
    <span>招募人数</span>
    <a-input-group compact>
      <a-input
        v-model:value="volunteerInfo.recruitNumber"
        class="site-input-right"
        style="width: 100px; text-align: center"
        placeholder="最多"
        @input="handleInput"
      />
    </a-input-group>
    <span>招募岗位</span>
    <a-input-group compact>
      <a-input
        v-model:value="volunteerInfo.recruitmentPositions"
        style="width: 50%"
      />
    </a-input-group>
    <h2><b>报名须知</b></h2>
    <span>报名限制</span>
    <a-input-group compact>
      <a-input
        v-model:value="volunteerInfo.enrollmentRestrictions"
        style="width: 50%"
      />
    </a-input-group>
    <span>报名截止时间</span>
    <a-input-group compact>
      <a-date-picker
        show-time
        v-model:value="timeStorage2"
        :disabled-date="disabledDate"
        :disabled-time="disabledTime"
        @change="handleTimeChange2"
      />
    </a-input-group>
    <h2><b>活动介绍</b></h2>
    <span>活动简介</span>
    <a-input-group compact>
      <a-input
        v-model:value="volunteerInfo.eventDescription"
        style="width: 60%"
        placeholder="请用一句话介绍该志愿活动"
      />
    </a-input-group>
    <span>活动内容</span>
    <br />
    <a-textarea
      v-model:value="volunteerInfo.eventContent"
      style="width: 60%"
      size="large"
      placeholder="请描述活动内容"
      allow-clear
    />
    <h2><b>活动图片</b></h2>
    <a-form-item label="">
      <a-upload
        v-model:file-list="fileList"
        :headers="headers"
        action="/aPi/web/admin/common/upload"
        list-type="picture-card"
        :before-upload="beforeUpload"
        @preview="handlePreview"
        @change="handleChange"
      >
        <div v-if="fileList.length < 1">
          <loading-outlined v-if="loading"></loading-outlined>
          <PlusOutlined />
          <div style="margin-top: 8px">上传</div>
        </div>
      </a-upload>
      <a-modal
        :open="previewVisible"
        :title="previewTitle"
        :footer="null"
        @cancel="handleCancel"
      >
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </a-form-item>
  </div>
  <a-space class="site-input-group-wrapper" direction="vertical" size="middle">
  </a-space>
  <a-space wrap>
    <a-button type="primary" block size="large" @click="SubmitVolunteer()">
      发布志愿
    </a-button>
  </a-space>
</template>
<style scoped>
/* 错误提示样式 */
.ant-alert {
  margin-top: 5px;
}

.site-input-group-wrapper .site-input-split {
  background-color: #fff;
}

.site-input-group-wrapper .site-input-right {
  border-left-width: 0;
}

.site-input-group-wrapper .site-input-right:hover,
.site-input-group-wrapper .site-input-right:focus {
  border-left-width: 1px;
}

.site-input-group-wrapper .ant-input-rtl.site-input-right {
  border-right-width: 0;
}

.site-input-group-wrapper .ant-input-rtl.site-input-right:hover,
.site-input-group-wrapper .ant-input-rtl.site-input-right:focus {
  border-right-width: 1px;
}

[data-theme='dark'] .site-input-group-wrapper .site-input-split {
  background-color: transparent;
}
</style>
